%% Author: tangj
%% Created: 2012-9-18
%% Description: TODO: Add description to server_app
-module(server_app).
-behaviour(application).

-export([
		 start/2,
		 stop/1
		]).

%% --------------------------------------------------------------------
start(_Type, _StartArgs) ->
	{ok, SupPid} = server_sup:start_link(),
	
	AcceptorCount = tool:get_config(server, acceptor_count),
	ListenPort = tool:get_config(server, port),
	ListenIp = tool:get_config(server, ip),
	
	io:format("node ~p server_app~p ~nserver start ~p:~p~n", 
			  [node(), self(), ListenIp, ListenPort]),
	
	ok = start_tcp(AcceptorCount, ListenPort),
	ok = start_client(),
	
	{ok, SupPid}.

stop(_State) ->
	ok.

%% 监听accpet
start_tcp(AcceptorCount, Port) ->
	{ok, _} = supervisor:start_child(
				server_sup,
				{tcp_listener_sup,
				 {tcp_listener_sup, start_link, [AcceptorCount, Port]},
				 transient, infinity, supervisor, [tcp_listener_sup]}),
	ok.

%% 处理客户端连接
start_client() ->
	{ok,_} = supervisor:start_child(
			   server_sup,
			   {tcp_client_sup,
				{tcp_client_sup, start_link,[]},
				transient, infinity, supervisor, [tcp_client_sup]}),
	ok.